import  axios from 'axios'
import store from '@/store/index'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.baseURL = '';
//请求拦截器
axios.interceptors.request.use(
    config => {
        config.headers['Authorization'] =  'Bearer ' + store.state.app.token;
        return config;
    },
    error => {

        return Promise.reject(error);
    }
);

//响应拦截器
axios.interceptors.response.use(
    response => {

        return response.data;
    },
    error => {
        return Promise.reject(error);
    }
);

export function $request(options={}){
    if (option.type) {
        option.type.toLowerCase()
    } else {
        option.type = 'get'
    }
    return new Promise((resolve, reject) => {
        if (option.type == 'post') {
            axios.post(url, option.data,{
                headers: {
                    'Content-Type': 'application/json'
                },
                transformRequest: [(data) => {
                    // 如果是对象才序列化
                    return typeof data === 'object' ? JSON.stringify(data) : data
                }]
            })
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err)
                })
        } else if (option.type == 'get') {
            axios.get(url, {
                params: option.data
            })
                .then(response => {
                    resolve(response.data);
                })
                .catch(err => {
                    reject(err)
                })
        }
    })
}
